<script lang="ts" setup>
import { ElMessage } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import {
  convertSTLToOBJ,
  convertSTLToPLY,
  convertOBJToSTL,
  convertOBJToPLY,
  convertPLYToSTL,
  convertPLYToOBJ
} from '@/api/system/convert'
import { resetData } from '@/hooks/use-common'
import { i18n } from '@/lang'
const { t } = i18n.global

/** 提交按钮 */
const open = ref(false)
const title = ref('')
const emits = defineEmits([])
const fileType = ref('')
const targetType = ref('')

const addEditForm = reactive({
  originalName: '',
  fileSuffix: ''
})

const formString = JSON.stringify(addEditForm)
const uploadRef = ref()

/** 取消按钮 */
const cancel = () => {
  open.value = false
  resetData(addEditForm, formString)
  // emits('getList')
}

const showModal = () => {
  title.value = t('convert.convertFile')
  open.value = true
}

// 下载blog文件
const downloadBlogFile = (blob, filename) => {
  // 创建一个指向Blob的URL
  const url = URL.createObjectURL(blob)

  // 创建一个a标签用于下载文件
  const downloadLink = document.createElement('a')
  downloadLink.href = url
  downloadLink.download = filename // 指定下载文件名

  // 触发下载
  document.body.appendChild(downloadLink)
  downloadLink.click()

  // 清理并移除元素和对象URL
  document.body.removeChild(downloadLink)
  URL.revokeObjectURL(url)
}

const hanldeHttpRequest = (options) => {
  const formData = new FormData()
  formData.append('file', options.file)

  console.log(fileType, targetType)

  switch (fileType.value) {
    case 'STL':
      if (targetType.value == 'OBJ') {
        convertSTLToOBJ(formData).then((res: any) => {
          const blob = new Blob([res], { type: 'text/plain' })
          const filename = options.file.name.replace(fileType, targetType)
          downloadBlogFile(blob, filename)
        })
      } else if (targetType.value == 'PLY') {
        convertSTLToPLY(formData).then((res: any) => {
          const blob = new Blob([res], { type: 'text/plain' })
          const filename = options.file.name.replace(fileType, targetType)
          downloadBlogFile(blob, filename)
        })
      }
      break
    case 'OBJ':
      if (targetType.value == 'STL') {
        convertOBJToSTL(formData).then((res: any) => {
          const blob = new Blob([res], { type: 'text/plain' })
          const filename = options.file.name.replace(fileType, targetType)
          downloadBlogFile(blob, filename)
        })
      } else if (targetType.value == 'PLY') {
        convertOBJToPLY(formData).then((res: any) => {
          const blob = new Blob([res], { type: 'text/plain' })
          // 创建一个指向Blob的URL
          const url = URL.createObjectURL(blob)
          const filename = options.file.name.replace(fileType, targetType)
          downloadBlogFile(blob, filename)
        })
      }
      break

    case 'PLY':
      if (targetType.value == 'STL') {
        convertPLYToSTL(formData).then((res: any) => {
          const blob = new Blob([res], { type: 'text/plain' })
          const filename = options.file.name.replace(fileType, targetType)
          downloadBlogFile(blob, filename)
        })
      } else if (targetType.value == 'OBJ') {
        convertPLYToOBJ(formData).then((res: any) => {
          const blob = new Blob([res], { type: 'text/plain' })
          const filename = options.file.name.replace(fileType, targetType)
          downloadBlogFile(blob, filename)
        })
      }
      break
  }
}
const options: any = ref([])
const defaultOptions = ['STL', 'OBJ', 'PLY']

const getFileFormat = (filename) => {
  const index = filename.lastIndexOf('.')
  // eslint-disable-next-line unicorn/prefer-string-slice
  return index == -1 ? '' : filename.substring(index + 1)
}

const onChange = (fileinfo) => {
  fileType.value = getFileFormat(fileinfo.name).toUpperCase()
  options.value = defaultOptions.filter((it) => it !== fileType.value.toUpperCase())
}

const submit = () => {
  uploadRef.value?.submit()
}

const clear = () => {
  options.value = []
  fileType.value = ''
  targetType.value = ''
}

onMounted(() => {})
//导出给refs使用
//用于子组件向其父组件传值
defineExpose({ cancel, showModal })
</script>

<template>
  <el-dialog
    v-model="open"
    :title="title"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    :destroy-on-close="true"
    width="500px"
    append-to-body
    @close="cancel"
  >
    <el-upload
      ref="uploadRef"
      class="upload-demo"
      drag
      :limit="1"
      accept=".obj,.ply,.stl"
      :auto-upload="false"
      :show-file-list="false"
      :on-change="onChange"
      :http-request="hanldeHttpRequest"
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">
        Drop file here or
        <em>click to upload</em>
      </div>
      <div class="el-upload__tip">please select .stl,.obj,.ply</div>
    </el-upload>
    <div v-if="fileType" class="convert-select">
      <el-input v-model="fileType" size="large" readonly style="width: 140px" />
      <div>=></div>
      <el-select v-model="targetType" placeholder="Select" size="large" style="width: 240px">
        <el-option v-for="item in options" :key="item" :label="item" :value="item" />
      </el-select>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="clear">{{ t('convert.clear') }}</el-button>
        <el-button type="primary" @click="submit">{{ t('convert.startNow') }}</el-button>
        <el-button type="primary" @click="cancel">{{ t('convert.confirm') }}</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.convert-select {
  display: flex;
  align-items: center;
  margin-top: 1rem;
  justify-content: space-between;
}
</style>
